//
//  TZNewWorkTool.swift
//  WeiboWithSwift
//
//  Created by 涂真 on 15/12/19.
//  Copyright © 2015年 涂真. All rights reserved.
//

import UIKit
import AFNetworking
//定义枚举管理错误
enum TZNetWorkError:Int{
    case emptyAccessToken = -1
    case emptyUid = -2
    var errorDescription:String{
        switch self{
        case TZNetWorkError.emptyAccessToken:
            return "access_token没值"
        case TZNetWorkError.emptyUid:
            return "uid没有值"
        }
    }
    
    func error()->NSError{
    return NSError(domain: "cn.tuzhen.error.network", code: self.rawValue, userInfo: ["errorDescription":self.errorDescription])
    }
}

class TZNetWorkTool: AFHTTPSessionManager {
    ///单例对象
    //    static let shardNetWorkTool:TZNetWorkTool = {
    //        let baseURL = NSURL(string: "https://api.weibo.com/")
    //        let netWorkTool = TZNetWorkTool(baseURL: baseURL)
    //        return netWorkTool
    //
    //    }()
    
    static let shardNetWorkTool:TZNetWorkTool = TZNetWorkTool()
    
    init(){
        let baseURL = NSURL(string: "https://api.weibo.com/")
        super.init(baseURL: baseURL, sessionConfiguration: nil)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: - 授权相关条件
    ///appKey
    private let client_id = "734397000"
    //app 秘钥
    private let client_secret = "32120f5e3204e9911c654a337c41db24"
    ///授权回调地址
    let redirect_uri = "http://www.baidu.com/"
    
    //Mark: - 拼接登陆URL
    func oauthUrl() -> NSURL{
        let urlStr = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        //AFN默认不支持解析text/plain格式的数据,需要手动添加解析类型
        self.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return NSURL(string: urlStr)!
    }
    
    //MARK: - 加载AccessToken
    func loadAccessToken(code:String,finished:(result:[String:AnyObject]?,error:NSError?)->()){
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        let parameters = [
            "client_id":client_id,
            "client_secret":client_secret,
            "grant_type":"authorization_code",
            "code":code,
            "redirect_uri":redirect_uri
        ]
        POST(urlStr, parameters: parameters, success: { (_, result) -> Void in
            let dict = result as? [String:AnyObject]
            finished(result: dict, error: nil)
            
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
    
    //MRKL: - 获取账户信息
    func loadAccountInfo(finished:(result:[String:AnyObject]?,error:NSError?)->Void){
        let urlStr = "https://api.weibo.com/2/users/show.json"
        //守卫
        guard let access_token = TZUserAccount.loadAccountInfo()?.access_token else{
            //进来就是access_token没值
            let error = TZNetWorkError.emptyAccessToken.error()
            finished(result: nil, error: error)
            return
        }
        guard let uid = TZUserAccount.loadAccountInfo()?.uid else{
            let error = TZNetWorkError.emptyUid.error()
            finished(result: nil, error: error)
            return
        }
        //access_token,uid都有值
        let parameters = ["access_token":access_token,"uid":uid]
        GET(urlStr, parameters: parameters, success: { (_, result) -> Void in
            let dict = result as? [String:AnyObject]
            finished(result: dict, error: nil)
            //TODU:打印用户信息
//            print(result)
            //TODU:打印AccessToken
            print("AccessToken:\(access_token)")
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
                
        }
    }
    
    //MARK: - 获取微博信息
    ///网络加载微博信息
    func loadStatus(finished:(result:[String:AnyObject]?,error:NSError?)->()){
    
        guard let access_token = TZUserAccount.loadAccountInfo()?.access_token else{
        let error = TZNetWorkError.emptyAccessToken.error()
            finished(result: nil, error: error)
        return
        }
        
        let urlStr = "2/statuses/public_timeline.json"
        let parameters = ["access_token":access_token]
        GET(urlStr, parameters: parameters, success: { (_, result) -> Void in
        let dict = result as? [String:AnyObject]
            finished(result: dict, error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
}
